/*
 * File     : StructureByReferenceParameter.java
 * Created  : 3 May 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.call;

import static com.googlecode.dni.internal.DniTypes.POINTER_TYPE;
import static com.googlecode.dni.internal.DniTypes.STRUCTURE_TYPE;
import static org.objectweb.asm.Opcodes.ARETURN;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;

import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import com.googlecode.dni.internal.DniInternal;
import com.googlecode.dni.type.structure.Structure;

/**
 * <p>
 *  Encapsulates a parameter to a native call that comes from a
 *  {@link Structure} by reference.
 * </p>
 *
 * @author Matthew Wilson
 */
final class StructureByReferenceParameter extends NativeObjectParameter
{

    /**
     * {@inheritDoc}
     */
    @Override
    void setJavaType( final Class< ? > javaType )
    {
        super.setJavaType( javaType );

        // ensure the structure is loaded
        DniInternal.getStructureRecord( javaType.asSubclass( Structure.class ) );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writeReturnParameter( final MethodVisitor methodVisitor, final int returnVarIndex )
    {
        String factoryName =
            DniInternal.getStructureFactoryImplName( getJavaType().asSubclass( Structure.class ) );

        String implName =
            DniInternal.getStructureImplName( getJavaType().asSubclass( Structure.class ) );

        methodVisitor.visitFieldInsn( GETSTATIC,
                                      factoryName,
                                      "INSTANCE",
                                      "L" + factoryName + ";" );
        writeAddressToPointer( methodVisitor, returnVarIndex );

        methodVisitor.visitMethodInsn( INVOKEVIRTUAL,
                                       factoryName,
                                       "fromPointer",
                                       "(L" + POINTER_TYPE + ";)L" + STRUCTURE_TYPE + ";" );

        methodVisitor.visitTypeInsn( Opcodes.CHECKCAST, implName );

        methodVisitor.visitInsn( ARETURN );
    }

}
